package com.laycoding.layrpc.config.client;


import com.laycoding.layrpc.common.SpringUtils;
import com.laycoding.layrpc.entity.LayRpcMessage;
import com.laycoding.layrpc.service.RpcService;
import com.laycoding.layrpc.service.RpcServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.UUID;


public class ServiceProxy<T> implements InvocationHandler {



    private Class<T> interfaceType;

    public ServiceProxy(Class<T> intefaceType) {
        this.interfaceType = interfaceType;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
        }
        LayRpcMessage invokerMessage = new LayRpcMessage();
        invokerMessage.setRpcId(UUID.randomUUID().toString());
        invokerMessage.setClassName(method.getDeclaringClass().getName());
        invokerMessage.setMethodName(method.getName());
        invokerMessage.setValues(args);
        invokerMessage.setParams(method.getParameterTypes());
        RpcServiceImpl rpcService = (RpcServiceImpl) SpringUtils.getObject("rpcService");
        Object obj = null;
        try {
            obj = rpcService.sendMessage(invokerMessage);
        } catch (Exception e) {
            return obj;
        }
        
        return obj;
    }
}

